function number2string  (num) {
	num = String(num)
  
	var eSplit = num.split('e')
  
	var e = +(eSplit[1] || 0)
  
	var pad = '0'.repeat(500)
  
	var numSplit = eSplit[0].split('.')
  
	var str
  
	var numSplit1 = numSplit[1] || ''
  
	if (e < 0) {
	  str = ('0.' + (pad + numSplit[0]).slice(e) + numSplit1)
	} else {
	  str = (numSplit[0] + (numSplit1 + pad).slice(0, e) + '.' + numSplit1.slice(e))
	}
  
	return str.replace(/\.?0*$/, '').replace(/^0*/, '').replace(/^\./, '0.') || '0'
}
  
function accMul  (arg1, arg2) {
	var m = 0
	var s1 = arg1.toString()
	var s2 = arg2.toString()
	try {
	  m += s1.split('.')[1].length
	} catch (e) {}
	try {
	  m += s2.split('.')[1].length
	} catch (e) {}
	return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m)
}
  

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatDateTime(date, fmt = 'yyyy-MM-dd hh:mm:ss') {
	if (!date) {
		return ''
	}
	if (typeof(date) === 'number') {
		date = new Date(date.replace(/-/g, "/") * 1000)
	}
	var o = {
		"M+": date.getMonth() + 1, //月份
		"d+": date.getDate(), //日
		"h+": date.getHours(), //小时
		"m+": date.getMinutes(), //分
		"s+": date.getSeconds(), //秒
		"q+": Math.floor((date.getMonth() + 3) / 3), //季度
		"S": date.getMilliseconds() //毫秒
	}
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length))
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)))
	return fmt
}

function getCountDown(endTime) {
	function checkTime(i) {
		if (i < 10) {
			i = '0' + i
		}
		return i
	}
	let endT = new Date(endTime.replace(/-/g, "/"))
	let startT = new Date()
	let diff = endT.getTime() - startT.getTime()
	let day = parseInt(diff / 1000 / 60 / 60 / 24) //天
	let hours = parseInt(diff / 1000 / 60 / 60 % 24) //时
	let minutes = parseInt(diff / 1000 / 60 % 60) //分
	let seconds = parseInt(diff / 1000 % 60) //秒
	return checkTime(day) + '天' + checkTime(hours) + '时' + checkTime(minutes) + '分' + checkTime(seconds) + '秒'
}

function getDistance(lat1, lng1, lat2, lng2) {
	// lat1用户的纬度
	// lng1用户的经度
	// lat2商家的纬度
	// lng2商家的经度
	var radLat1 = Rad(lat1);
	var radLat2 = Rad(lat2);
	var a = radLat1 - radLat2;
	var b = Rad(lng1) - Rad(lng2);
	var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math
		.sin(
			b / 2), 2)));
	s = s * 6378.137;
	s = Math.round(s * 10000) / 10000;
	s = s.toFixed(2) + 'km' //保留两位小数
	return s
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}

function formatGetDateDiff(startTime, endTime, diffType) {
	//将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式 
	startTime = startTime.replace(/\-/g, "/");
	endTime = endTime.replace(/\-/g, "/");
	//将计算间隔类性字符转换为小写
	diffType = diffType.toLowerCase();
	var sTime = new Date(startTime); //开始时间
	var eTime = new Date(endTime); //结束时间
	//作为除数的数字
	var timeType = 1;
	switch (diffType) {
		case "second":
			timeType = 1000;
			break;
		case "minute":
			timeType = 1000 * 60;
			break;
		case "hour":
			timeType = 1000 * 3600;
			break;
		case "day":
			timeType = 1000 * 3600 * 24;
			break;
		default:
			break;
	}
	return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(timeType));
}
// alert(GetDateDiff("2016-03-28 10:30:22","2016-03-28 10:38:22","minute"));

function getBase64ImageUrl(data) {
	/// 获取到base64Data
	var base64Data = data;
	/// 通过微信小程序自带方法将base64转为二进制去除特殊符号，再转回base64
	base64Data = wx.arrayBufferToBase64(wx.base64ToArrayBuffer(base64Data));
	/// 拼接请求头，data格式可以为image/png或者image/jpeg等，看需求
	const base64ImgUrl = "data:image/png;base64," + base64Data;
	/// 刷新数据
	return base64ImgUrl;
}

function throttle(fn, context, delay, text) {
	clearTimeout(fn.timer);
	fn.timer = setTimeout(() => {
		fn.call(context, text);
	}, delay);
}

function debounce(func, wait, immediate = true) {
	let timeout = null
	return function() {
		if (timeout) clearTimeout(timeout)
		timeout = setTimeout(() => {
			func.apply(this, arguments, wait)
		})
	}
}
async function dianji(fn) {
	let that = this;
	if (that.onoff) {
		that.onoff = false;
		await fn()
		setTimeout(() => {
			that.onoff = true;
		}, 5000)


	} else {
		//如果一直走else分支可能是你没有在页面的data下面挂载onoff:true,不然一直都会走else
	}
}
let success = 'success'
let PENDING = 'pening'
let error = 'error'
class Promise {
	constructor(callback) {
		callback(this.resolve, this.reject)
	}
	status = PENDING;
	value = null;
	Rerror = null;
	resolve(value) {
		if (status == PENDING) {
			status = success
			this.value = value
		}
	}
	reject(Rerror) {
		if (status == PENDING) {
			status = error
			this.Rerror = Rerror
		}

	}
	then(resolve, reject) {
		if (status == success) {
			resolve(this.value)
		} else if (status == error) {
			reject(this.Rerror)
		}
	}
}
var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDate()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	},
};

function ossUpload(file, fileUrl, fn) {
	const storeAs = setFileName(fileUrl)
	const msg = this.$store.state.aliToken;
	uni.uploadFile({
		url: ports.ALL_PUBLIC_PATH, // 如：https://testbucketname.oss-cn-huhehaote.aliyuncs.com
		filePath: file, //choostimage 返回的临时图片路径
		name: 'file',
		formData: { //下面的属性名称 大小写无所谓 都能通过
			'Key': storeAs.fileUrl, //OSS存储路径/图片名称 => 如：task/test.jpg 别写成 /test.jpg 会有问题
			'Policy': msg.policy, //后端Base64编码格式的授权策略 用于签名
			'OSSAccessKeyId': msg.accessKeyId, //OSS控制台获取
			'Signature': msg.signature, //服务端返回的签名内容
			'Success_Action_Status': '200', //让服务端返回200,不然，成功上传图片后阿里默认返回statusCode: 204
		},
		success: (path) => {
			fn(ports.ALL_PUBLIC_PATH + storeAs.fileUrl)
		},
		fail: (e) => {}
	})
}

function setFileName(name) {
	var fileObj = {};
	var doctorId = uni.getStorageSync('user').pid;
	fileObj.typeName = getFileType(name);
	fileObj.fileName = 'hr_' + doctorId + '_' + getTimeNum() + '.' + fileObj.typeName;
	fileObj.fileUrl = 'ic_hr' + '/' + fileObj.fileName;
	return fileObj;
}

function seTequestSubscribeMessage(arr, callback) {
	uni.requestSubscribeMessage({
		tmplIds: arr,
		success(res) {
			callback(res)
		},
		fail(err) {
			callback(err)
		}
	})
}

// 随机数 (第一个参数数组。第二个参数为生成数量)
 function getRandomArrayElements(arr, count) {
	         var shuffled = arr.slice(0),
	             i = arr.length,
	             min = i - count,
	             temp, index;
	         while (i-- > min) {
	             index = Math.floor((i + 1) * Math.random());
	             temp = shuffled[index];
	             shuffled[index] = shuffled[i];
	             shuffled[i] = temp;
	         }
	         return shuffled.slice(min)
 }
 // 图片转为base64
function getBase64(url, callback) {
	if(url != ''){
 		let Img = new Image(),
 			dataURL = '';
 		let imgExt = url
 		Img.src = url + "?v=" + Math.random(); // 处理缓存,fix缓存bug,有缓存，浏览器会报错;
 		Img.setAttribute("crossOrigin", 'Anonymous') // 解决控制台跨域报错的问题（没用就跟后台沟通添加跨域）
 		Img.onload = function() { //要先确保图片完整获取到，这是个异步事件
 			let canvas = document.createElement("canvas"), //创建canvas元素
 				width = Img.width, //确保canvas的尺寸和图片一样
 				height = Img.height;
 			canvas.width = width;
 			canvas.height = height;
 			canvas.getContext("2d").drawImage(Img, 0, 0, width, height); //将图片绘制到canvas中
 			dataURL = canvas.toDataURL('image/' + imgExt); //转换图片为dataURL 
 			callback ? callback(dataURL) : null; //调用回调函数
 		}
	}
 
 }
			
module.exports = {
	number2string,
	accMul,
	formatTime,
	formatDateTime,
	formatLocation,
	formatGetDateDiff,
	dateUtils,
	throttle,
	debounce,
	dianji,
	getDistance,
	getBase64ImageUrl,
	ossUpload,
	getCountDown,
	seTequestSubscribeMessage,
	getRandomArrayElements,
	getBase64
}
